package com.hyperion.blog.config;

import com.alibaba.fastjson.JSON;
import com.hyperion.blog.dao.mapper.ArticleMapper;
import com.hyperion.blog.dao.pojo.Article;
import com.hyperion.blog.service.ThreadService;
import com.hyperion.blog.vo.ArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * @author Hyperion
 * @date 2021/10/30
 */
@Component
@Slf4j
public class Scheduler {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ThreadService threadService;

    /**
     * 测试用
     */
    @Scheduled(fixedRate = 10 * 1000)
    public void articleViewCountsWriteBack() {
        String redisKey = "findArticleById::ArticleServiceImpl::findArticleById::*";
        Set<String> redisKeys = redisTemplate.keys(redisKey);
        if (redisKeys != null && !redisKeys.isEmpty()) {
            log.info("=====================定时任务开始: 将文章的浏览量回写进数据库=====================");
            log.info("本次回写浏览量的文章数量：{}", redisKeys.size());
            for (String key : redisKeys) {
                String redisValue = redisTemplate.opsForValue().get(key);
                if (StringUtils.isNotEmpty(redisValue)) {
                    ArticleVo articleVo = JSON.parseObject(redisValue, ArticleVo.class);
                    Article article = new Article();
                    article.setId(Long.valueOf(articleVo.getId()));
                    article.setViewCounts(articleVo.getViewCounts());
                    threadService.updateViewCount(articleMapper, article);
                }
            }
            log.info("=====================定时任务结束: 将文章的浏览量回写进数据库=====================");
        }
    }
}
